from ivic.core import Logging
from ivic.core import Config, project_path
from ivic.vsched import Model
from ivic.vsched.Server import ServerClass
from ivic.vsched.Controller import JobDispatcher

logger = Logging.get_logger('ivic.vsched.Plugin')

__obj = None
__jobdispatcher = None

def init(daemon_config):
    config = Config.load(project_path('/etc/ivic/vsched.yaml'))
    # this should dispatch 'ivic.vsched.*' to individual log file
    Logging.get_logger('ivic.vsched', filename = config['log_file'])
    # after logger initialzed, register Model obj debug formatter
    Model.register_generic_repr()

    logger.debug('initializing %s(soap)' % __name__)
    global __obj
    if __obj:
        logger.error('reinitialized is not supported')
        return
    __obj = ServerClass(config)

    logger.debug('initializing %s(controller)' % __name__)
    Session = Model.get_ScopedSession(config['connect_string'])

    global __jobdispatcher
    __jobdispatcher = JobDispatcher(
        Session, 
        thread_num = config['thread_num'],
        debug_soap = config['debug_soap'],
        task_timeout = config['task_timeout'],
    )
    __jobdispatcher.start()

def fini():
    global __obj 
    del __obj

    global __jobdispatcher
    __jobdispatcher.stop()
    __jobdispatcher.join()

def soap_mods():
    global __obj
    return {'vsched': __obj}

def wsgi_mods():
    return {}
